//
//  AdminListVC.m
//  dianfan
//
//  Created by Ye Jin on 15/11/10.
//  Copyright © 2015年 Ye Jin. All rights reserved.
//

#import "AdminListVC.h"
#import <BmobSDK/bmob.h>
#import "DetailOrderVC.h"
#import "MBProgressHUD.h"
#import "Order.h"

@interface AdminListVC ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *priceSum;

@property (nonatomic, copy) NSString *startString;
@property (nonatomic, copy) NSString *endString;
@property (nonatomic) NSMutableArray *orders;
@property (nonatomic) NSArray *sortOrders;

@property (nonatomic, weak) UIView *dateView;
@property (nonatomic, weak) UIDatePicker *datepicker;

@end

@implementation AdminListVC

- (void)confirm: (id)sender
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    self.startString = [dateFormatter stringFromDate:self.datepicker.date];
    self.title = self.startString;
    NSDate *enddate = [NSDate dateWithTimeInterval:24*60*60 sinceDate:self.datepicker.date];
    self.endString = [dateFormatter stringFromDate:enddate];
    [self.dateView removeFromSuperview];
    [self loadData];
}

- (void)cancel
{
    [self.dateView removeFromSuperview];
}

- (void)fliter
{
    UIView *subview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    self.dateView = subview;
    self.dateView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    [self.view addSubview:self.dateView];
    UIDatePicker *mydatepicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 250, self.view.bounds.size.width, 250)];
    self.datepicker = mydatepicker;
    [self.datepicker setDatePickerMode:UIDatePickerModeDate];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    self.datepicker.date = [dateFormatter dateFromString:self.startString];

    
    
    self.datepicker.backgroundColor = [UIColor whiteColor];
    [self.dateView addSubview:self.datepicker];
    UIButton *confirm = [[UIButton alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height-300, self.view.bounds.size.width/2.0, 50)];
    [confirm setTitle:@"确认" forState:UIControlStateNormal];
    [confirm setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    confirm.backgroundColor = [UIColor whiteColor];
    UIButton *cancel = [[UIButton alloc] initWithFrame:CGRectMake(self.view.bounds.size.width/2.0, self.view.bounds.size.height-300, self.view.bounds.size.width/2.0, 50)];
    cancel.backgroundColor = [UIColor whiteColor];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.dateView addSubview:confirm];
    [self.dateView addSubview:cancel];
    
    [confirm addTarget:self action:@selector(confirm:) forControlEvents:UIControlEventTouchUpInside];
    [cancel addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd"];
    
    //    NSDate *date = [NSDate date];
    //    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    //    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *startDate = [NSDate date];
    NSDate *endDate = [NSDate dateWithTimeInterval:24*60*60 sinceDate:startDate];
    self.startString = [dateformatter stringFromDate:startDate];
    self.endString = [dateformatter stringFromDate:endDate];
    self.title = self.startString;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"更改日期"
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:self
                                                                            action:@selector(fliter)];
    [self loadData];
}

- (void)loadData
{
    __block int sumPrice = 0;
    self.priceSum.text = [NSString stringWithFormat:@"总价: 0"];
    //原本在viewDidLoad里面
    self.orders = [[NSMutableArray alloc] init];
    self.sortOrders = [[NSArray alloc] init];
    
    //转菊花
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode=MBProgressHUDAnimationFade;//枚举类型不同的效果
    hud.labelText=@"loading";
    
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"Order"];
    NSString *bql = @"select sum(dishNum) from Order where createdAt > date(?) and createdAt < date(?) group by dish";
    [bquery statisticsInBackgroundWithBQL:bql pvalues:@[[NSString stringWithFormat:@"%@ 00:00:00",self.startString],[NSString stringWithFormat:@"%@ 00:00:00",self.endString]] block:^(NSArray *result, NSError *error) {
        if (error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@",error] message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        } else {
            if (result) {
                if ([result count]==0) {
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                }
                for (NSDictionary *dish in result) {
                    BmobQuery *bq = [BmobQuery queryWithClassName:@"Menu"];
                    [bq includeKey:@"restaurant"];
                    [bq getObjectInBackgroundWithId:[[dish objectForKey:@"dish"] objectForKey:@"objectId"] block:^(BmobObject *object, NSError *error) {
                        if (error) {
                            [MBProgressHUD hideHUDForView:self.view animated:YES];
                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@",error] message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                            [alert show];
                        }
                        else
                        {
                            Order *order = [[Order alloc] init];
                            order.restaurantName = [[object objectForKey:@"restaurant"] objectForKey:@"restaurantName"];
                            order.dishName = [object objectForKey:@"dishName"];
                            order.dishNum = [[dish objectForKey:@"_sumDishNum"] intValue];
                            [self.orders addObject:order];
                            sumPrice += [[object objectForKey:@"Price"] intValue]*order.dishNum;
                        }
                        if ([self.orders count] == [result count]) {
                            [MBProgressHUD hideHUDForView:self.view animated:YES];
                            //这里类似KVO的读取属性的方法，直接从字符串读取对象属性，注意不要写错
                            NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"_restaurantName" ascending:YES];
                            //这个数组保存的是排序好的对象
                            self.sortOrders = [self.orders sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
                            self.priceSum.text = [NSString stringWithFormat:@"总价: %d",sumPrice];
                            [self.tableView reloadData];
                        }
                    }];
                }
            }
        }
    }];
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.sortOrders count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"list";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    Order *order = [self.sortOrders objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@: %d",order.restaurantName,order.dishName,order.dishNum];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    DetailOrderVC *dovc = [sb instantiateViewControllerWithIdentifier:@"detailorder"];
    dovc.order = [self.sortOrders objectAtIndex:indexPath.row];
    dovc.startString = self.startString;
    dovc.endString = self.endString;
    [self.navigationController pushViewController:dovc animated:YES];
}


- (IBAction)pageRefresh:(id)sender {
    [self loadData];
}

@end
